﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;

namespace Liju.Common
{
     public class JsonHelper
    {
        /// <summary>
        /// json字符串转对象 类要+修饰 DataContract 属性要+修饰 DataMember
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(string strJson) 
        {
            DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));
            T obj = (T)s.ReadObject(ms);
            ms.Dispose();
            return obj;
        }

        /// <summary>
        /// 对象转json字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson<T>(T obj)
        {
            DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
            string strReturn = string.Empty;
            using (MemoryStream ms  = new MemoryStream())
            {
                s.WriteObject(ms,obj);
                ms.Position = 0;
                using (StreamReader sr = new StreamReader(ms))
                {
                    strReturn = sr.ReadToEnd();
                }
            }
            return strReturn;
        }

    }
}
